#!/bin/bash
cflag=
kflag=5
nflag=5
pflag=15
rflag=
while getopts ck:n:p:r name
do
        case $name in
                c) cflag=1;;
                k) if [ ! -z "$OPTARG" ]; then kflag="$OPTARG"; fi;;
                n) if [ ! -z "$OPTARG" ]; then nflag="$OPTARG"; fi;;
                p) if [ ! -z "$OPTARG" ]; then pflag="$OPTARG"; fi;;
                r) rflag="-r";;
                ?) printf "Usage: %s [-c] [-k value] [-n value] -r\n\t-c to use previous results\n\t-k to specify sort field (default 5)\n\t-n to specify how many lines to show (default 5)\n\t-p number of pings to send (default 15)\n\t-r to sort in reverse\n" $0
                   exit 1;;
        esac
done
if [ ! -z "%cflag" ] && [ ! -e runescape.pings ]
then
        echo "No previous run file, deactivating -c"
        cflag=
fi
if [ ! -z "$cflag" ]
then
        echo "Using previous values"
else
        echo -n "" > runescape.pings
        echo "Gathering pings...";
        for i in {1..139}
        do
                # world received lost min avg max mdev
                (ping -c $pflag -i 0.2 world$i.runescape.com |tail -n2 |sed -r '{N;s#.* ([0-9]+) received, ([0-9]+)% packet loss.*= ([0-9.]+)/([0-9.]+)/([0-9.]+)/([0-9.]+) ms.*# '$i' \1 \2 \3 \4 \5 \6 #g}' >> runescape.pings; echo -n . )&
        done
        wait
fi
echo -e "\nSorting..."
echo " _______________________________________________________________ "
echo -e "|\t|\t   Pings\t|\t Times (ms)\t\t|"
echo -e "| World\t|    Received\t| Lost%\t|  Min\t|  Avg\t|  Max\t|  Mdev\t|"
echo "|-------|---------------|-------|-------|-------|-------|-------|"

sort -k $kflag -n $rflag runescape.pings | head -n $nflag | sed -r '{
  s/([0-9]{3}\.[0-9])[0-9]* /\1 /g;
  s/([0-9]{2}\.[0-9]{2})[0-9]* /\1 /g;s/ /  /g;
  s/ (.) / _____\1_ /g ;
  s/ (..) / ____\1_ /g ;
  s/ (...) / ___\1_ /g ;
  s/ (....) / __\1_ /g ;
  s/ (.....) / _\1_ /g ;
  s/ (......) / \1_ /g ;
  s/ (.......) / \1 /g ;
  s/  /|/g;
  s/_/ /g;
  s/^(\| *[0-9]+ )\|( *[0-9]+ \| *[0-9]+ )\|/\1|\t \2|/g
}'
echo "'-------'---------------'-------'-------'-------'-------'-------'"